package com.shuiqian.talentpool.controller;

import com.shuiqian.talentpool.config.SysConfig;
import com.shuiqian.talentpool.entity.User;
import com.shuiqian.talentpool.enums.ResultsCodeEnum;
import com.shuiqian.talentpool.enums.UserEnum;
import com.shuiqian.talentpool.req.FileExcelReq;
import com.shuiqian.talentpool.resp.FileExcelResp;
import com.shuiqian.talentpool.resp.Results;
import com.shuiqian.talentpool.service.UserService;
import com.shuiqian.talentpool.utils.ExcelUtils;
import com.shuiqian.talentpool.utils.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import javafx.application.Application;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author landongqi
 * @create 2019-11-26 11:28
 */

@Api("文件导入接口")
@RestController
@CrossOrigin(origins = "*" , maxAge = 3600)
public class FileController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private SysConfig sysConfig;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "上传文件", notes="上传文件到服务器")
//    @ApiImplicitParam(name = "file", value = "文件", paramType = "query", required = true, dataType = "MultipartFile")
    @PostMapping(value = "/upload" ,produces = "application/json")
    @ResponseBody
    public Results upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Results(ResultsCodeEnum.upload_fail);
        }

        String fileName = file.getOriginalFilename();
        String filePath = sysConfig.getExcelPath();
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            return new Results(200,"上传成功");
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        return new Results(10001,"上传失败");
    }

    @ApiOperation(value = "上传多个文件", notes="上传多个文件到服务器")
//    @ApiImplicitParam(name = "file", value = "文件", paramType = "query", required = true, dataType = "MultipartFile")
    @PostMapping(value = "/uploadFiles" ,produces = "application/json")
    @ResponseBody
    public Results uploadFiles(@RequestParam("files") MultipartFile[] files) {
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            if (file.isEmpty()) {
                return new Results(ResultsCodeEnum.upload_fail);
            }

            String fileName = file.getOriginalFilename();
            String filePath = sysConfig.getExcelPath();
            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                LOGGER.info("上传成功:" + fileName);
            } catch (IOException e) {
                LOGGER.error(e.toString(), e);
            }
        }
        return new Results();
    }

    @ApiOperation(value = "文件目录对应", notes="获取文件目录对应数据")
    @PostMapping(value = "/correspond" ,produces = "application/json")
    @ResponseBody
    public Results correspond(@RequestBody FileExcelReq fileExcelReq) {
        if (fileExcelReq.getFileName() == null){
            return new Results(10001,"获取文件目录对应数据失败");
        }
        if (fileExcelReq.getSheetNo() == null){
            return new Results(10001,"获取文件目录对应数据失败");
        }
        if (fileExcelReq.getCatalogNo() == null){
            return new Results(10001,"获取文件目录对应数据失败");
        }
        String fileName = sysConfig.getExcelPath() + fileExcelReq.getFileName();
        try {
            FileExcelResp fileExcelResp = new FileExcelResp();
            Map<String,String> catalogList = new HashMap<>();
            Map<String,String> correspond = new HashMap<>();
            List<String> catalogListOfExcel = ExcelUtils.getCatalog(fileName, fileExcelReq.getSheetNo(), fileExcelReq.getCatalogNo());
            UserEnum[] values = UserEnum.values();
            for (int i = 0; i < catalogListOfExcel.size(); i++) {
                String catalog = catalogListOfExcel.get(i);
                correspond.put(catalog,"");
                for (int j = 0; j < values.length; j++) {
                    catalogList.put(values[j].getCode(),values[j].getMsg());
                    if (catalog.contains(values[j].getMsg())){
                        correspond.put(catalog,values[j].getCode());
                    }
                }
            }
            fileExcelResp.setCatalogList(catalogList);
            fileExcelResp.setCorrespond(correspond);
            return new Results(fileExcelResp);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Results(10001,"获取文件目录对应数据失败");
    }

    @ApiOperation(value = "解析文件", notes="解析文件并存入数据库")
    @PostMapping(value = "/analysis" ,produces = "application/json")
    @ResponseBody
    public Results analysis(@RequestBody FileExcelReq fileExcelReq) {
        if (fileExcelReq.getFileName() == null){
            return new Results(10001,"解析文件失败,请选择要解析的文件");
        }
        if (fileExcelReq.getCatalogNo() == null){
            return new Results(10001,"解析文件失败，请选择文件目录所在行");
        }
        if (fileExcelReq.getRowNo() == null){
            return new Results(10001,"解析文件失败，请选择文件数据起始行");
        }
        if (fileExcelReq.getCorrespond() == null){
            return new Results(10001,"解析文件失败，请选择目录对应列表");
        }
        String fileName = sysConfig.getExcelPath() + fileExcelReq.getFileName();
        try {
            List<Map> mapList = new ArrayList<>();
            List<List<String>> lists = ExcelUtils.readExcel(fileName, fileExcelReq.getSheetNo(), fileExcelReq.getRowNo());
            List<String> catalogListOfExcel = ExcelUtils.getCatalog(fileName, fileExcelReq.getSheetNo(), fileExcelReq.getCatalogNo());
            for (int i = 0; i < lists.size(); i++) {
                List<String> list = lists.get(i);
                Map<String, String> map = new HashMap<>();
                for (int j = 0; j < list.size(); j++) {
                    Map<String, String> correspond = fileExcelReq.getCorrespond();
                    map.put(correspond.get(catalogListOfExcel.get(j)),list.get(j));
                }
                mapList.add(map);
            }
            List<User> userList = MapUtil.convertMapListToBeanList(mapList, User.class);
            for (User user:userList){
                user.setId(UUID.randomUUID().toString());
                userService.saveUser(user);
            }
            return new Results();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Results(10001,"解析文件失败");
    }

    public static void main(String[] args) {
        String test = "编号";
        UserEnum[] values = UserEnum.values();
        String msg = values[35].getMsg();
        System.out.println(test.equals(msg));
        System.out.println(values[35].getMsg().contains(test));
    }
}
